// Copyright 2011 Miek Gieben. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// An AS112 blackhole DNS server. Similar to the one found in evldns.
// Also see https://www.as112.net/

package main

import (
	"fmt"
	"log"
	"os"
	"path/filepath"
	"runtime"
	"time"

	"github.com/kardianos/service"
)

var (
	logger  *log.Logger
	myHosts Hosts
)

const (
	version = "0.1"
)

func main() {

	dirpath, err := filepath.Abs(filepath.Dir(os.Args[0]))
	if err != nil {
		logger.Fatal(err)
		os.Exit(1)
	}
	err = os.Chdir(dirpath)
	if err != nil {
		logger.Fatal(err)
		os.Exit(1)
	}
	logger = initLogger(settings.LogFile)
    // 远程dns配置
	myHosts = Hosts{file: settings.HostConfig, hosts: map[string]string{}}
    // 定时检查dns配置是否变更
	myHosts.referer()
	go func() {
		timer := time.NewTicker(10 * time.Second)
		for {
			select {
			case <-timer.C:
				if myHosts.checkModify() {
					myHosts.referer()
				}
			}

		}

	}()

	svcConfig := &service.Config{
		Name:        "TaDns" + version,
		DisplayName: "Toaction Dns Service",
		Description: "Author http://www.toaction.cn/",
	}
	prg := &program{}
	s, err := service.New(prg, svcConfig)
	if err != nil {
		logger.Fatal(err)
	}
	if len(os.Args) > 1 {
		L("Run command:%s", os.Args[1])
		if os.Args[1] == "uninstall" {
			s.Stop()
		}
		err = service.Control(s, os.Args[1])
		if err != nil {
			logger.Fatal(err)
		}
		if os.Args[1] == "install" {
			s.Start()
		}
		fmt.Print("Run Ok")
		return
	}
	L("TaDns staring")
	err = s.Run()
	if err != nil {
		logger.Fatal(err)
	}

}

func Debug(format string, v ...interface{}) {
	if settings.Debug {
		logger.Printf(format, v...)
		fmt.Println(fmt.Sprintf(format, v))
	}
}
func L(format string, v ...interface{}) {
	logger.Printf(format, v...)
	fmt.Println(fmt.Sprintf(format, v...))
}

func initLogger(log_file string) (logger *log.Logger) {

	if log_file != "" {
		f, err := os.OpenFile(log_file, os.O_WRONLY|os.O_APPEND|os.O_CREATE, os.ModeAppend|0666)

		if err != nil {
			f, err = os.Create(log_file)
			if err != nil {
				os.Exit(1)
			}
		}
		logger = log.New(f, "[tadns]", log.Ldate|log.Ltime)
	} else {
		logger = log.New(os.Stdout, "[tadns]", log.Ldate|log.Ltime)
	}
	fmt.Println(fmt.Sprintf("[tadns]%s", time.Now()))
	return logger

}

func init() {
	runtime.GOMAXPROCS(runtime.NumCPU())
}
